//
//  OAuthViewController.swift
//  weibo19
//
//  Created by Arvin on 15/11/9.
//  Copyright © 2015年 Arvin. All rights reserved.
//

import UIKit
import AFNetworking
import MBProgressHUD

private let networkingTimeOut = 20

class OAuthViewController: UIViewController,UIWebViewDelegate {
    let web = UIWebView()
    
    override func loadView() {
        view = web
    }
    
    //MARK: 按钮点击事件
    func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    func aotuAddAccont() {
        // webView执行javascript代码
        // document.getElementById('userId').value = '18379203782'
        // document.getElementById('passwd').value = 'rlzygls200czh'
        let userStr = "document.getElementById('userId').value = '18379203782', document.getElementById('passwd').value = 'rlzygls200czh';"
        web.stringByEvaluatingJavaScriptFromString(userStr)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        addSubUI()
        loadOAuthPage()
    }
    
    /* 请求授权页面 接口https://api.weibo.com/oauth2/authorize
    GET 请求参数
    必选 	类型及范围 	说明
    client_id 	true 	string 	申请应用时分配的AppKey。
    redirect_uri 	true 	string 	授权回调地址，站外应用需与设置的回调地址一致，站内应用需填写canvas page的地址。
    */
    /* 请求token 接口https://api.weibo.com/oauth2/access_token
    POST请求参数
    必选 	类型及范围 	说明
    client_id 	true 	string 	申请应用时分配的AppKey。
    client_secret 	true 	string 	申请应用时分配的AppSecret。
    grant_type 	true 	string 	请求的类型，填写authorization_code
    
    必选 	类型及范围 	说明
    code 	true 	string 	调用authorize获得的code值。
    redirect_uri 	true 	string 	回调地址，需需与注册应用里的回调地址一致。
    */
    
    //MARK:请求授权页
    private func loadOAuthPage() {
        web.delegate = self
        let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=2921022464&redirect_uri=http://www.baidu.com")
        let request = NSMutableURLRequest(URL: url!)
        request.timeoutInterval = Double(networkingTimeOut)
        web.loadRequest(request)
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        MBProgressHUD.showMessage("正在加载")
        
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        MBProgressHUD.hideHUD()
    }
    
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        MBProgressHUD.hideHUD()
        let baidu = error?.userInfo["NSErrorFailingURLStringKey"]
        if (baidu?.containsString("https://m.baidu.com/") != nil) {
            return
        }
        MBProgressHUD.showError("网络加载错误...")
    }
    
    // 监听webViwe的请求过程
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let viewModel = UserAccountViewModel()
        // 如果urlStr 直接retur
        guard let urlStr = request.URL?.absoluteString else {
            return false
        }
        // https://api.weibo.com
        if urlStr.hasPrefix("https://api.weibo.com") {
            return true
        }
        // code在这个前缀里面 过滤掉回调的https://m.baidu.com/
        if !urlStr.hasPrefix(viewModel.redirect_uri) {
            return  false
        }
        // 获取code的
        guard let query = request.URL?.query else {
            return false
        }
        // 截取code的号码
        let codeStr = "code="
        let code = query.substringFromIndex(codeStr.endIndex)
        
        // 获取access_token
        viewModel.loadAccessToken(code) { (error) -> () in
            if error != nil {
                MBProgressHUD.showError(errorMessage)
            }
            MBProgressHUD.hideHUD()
            // model从控制器A-B, B控制器dismiss到A 本质上在底层还是A 在操作dismiss
            // 通知要放在dismiss回调的方法中, 保证OAuth控制器被A->dismiss(销毁)在发通知
            self.dismissViewControllerAnimated(false, completion: {() -> () in
                NSNotificationCenter.defaultCenter().postNotificationName(switchController, object: "OAuth")
            })
        }
        return true
    }
    
    private func addSubUI() {
        view.backgroundColor = UIColor.grayColor()
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style:UIBarButtonItemStyle.Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动添加", style:UIBarButtonItemStyle.Plain, target: self, action: "aotuAddAccont")
    }
}
